package com.noodles.mall.controller;

import com.noodles.mall.entity.Role;
import com.noodles.mall.entity.User;
import com.noodles.mall.service.RoleService;
import com.noodles.mall.service.UserRoleService;
import com.noodles.mall.service.UserService;
import com.noodles.mall.util.Constant;
import com.noodles.mall.util.Upload;
import com.noodles.mall.vo.PageVo;
import com.noodles.mall.web.JsonResult;
import com.noodles.mall.web.State;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** 用户 **/
@RestController
@RequestMapping("/user")
public class UserController {
    private static String dir="user";

    @Autowired
    Upload upload;

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    /** 增加 **/
    @RequestMapping("/insert")
    public JsonResult insert(@RequestBody User user) {
        System.out.println("UserController: register 开始");
        System.out.println("user: "+user);
        if (userService.selectOne(user.getUsername()) != null) {
            return JsonResult.error(State.ERR_EXIST, "用户名已存在");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user.setUsername(user.getUsername().trim());
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setIsEnabled(true);
        user=userService.insert(user);
        if(user==null) return JsonResult.error(State.ERR_SQL,"添加用户失败");
        Role role=roleService.selectOne(Constant.ROLE_MEMBER);
        if(role==null) return JsonResult.error(State.ERR_SQL,"查找角色失败");
        if(!userRoleService.insert(user.getId(),role.getId())){
            return JsonResult.error(State.ERR_SQL,"设置角色失败");
        }
        return JsonResult.success(user.getId());
    }

    /** 删除: 批量 **/
    @RequestMapping("/delete")
    public JsonResult delete(@RequestBody List<Integer> ids) {
        System.out.println("UserController: delete");
        System.out.println("idList: "+ids);
        return userService.delete(ids)
                ? JsonResult.success() : JsonResult.error(State.ERR_SQL);
    }

    /** 修改: **/
    @RequestMapping("/update")
    public JsonResult update(@RequestBody User user) {
        System.out.println("UserController: update");
        System.out.println("user: "+user);
        return userService.updateById(user)
                ? JsonResult.success() : JsonResult.error(State.ERR_SQL);
    }

    /** 修改: 上传头像 **/
    @RequestMapping("/upload/{id}")
    public JsonResult upload(@RequestBody MultipartFile file,
                             @PathVariable(value = "id") Integer id) {
        System.out.println("UserController: update");
        System.out.println("file: "+file);
        System.out.println("id: "+id);
        String avatarUrl= upload.save(file,dir+"/"+id);
        Map<String,Object> map=new HashMap<>();
        map.put("avatarUrl",avatarUrl);
        return userService.updateUrl(id,avatarUrl)
                ? JsonResult.success(map) : JsonResult.error(State.ERR_SQL);
    }

    /** 查找: 单个 **/
    @RequestMapping("/selectById/{id}")
    public JsonResult selectById(@PathVariable(value = "id") Integer id) {
        System.out.println("UserController: selectOne");
        System.out.println("id: "+id);
        User user = userService.selectOne(id);
        return JsonResult.success(user);
    }

    /** 查询用户数量 **/
    @RequestMapping("/selectCount")
    public JsonResult selectCount() {
        System.out.println("UserController: selectCount");
        int num = userService.selectCount();
        return JsonResult.success(num);
    }

    /** 分页查询: 页码, 数量 **/
    @RequestMapping("/selectPage/{current}/{size}")
    public JsonResult selectPage(@PathVariable(value = "current") Long current,
                                   @PathVariable(value = "size") Long size) {
        System.out.println("UserController: selectPage");
        System.out.println("current: "+current);
        System.out.println("size: "+size);
        PageVo<User> pageVo = userService.selectPage(current,size);
        return JsonResult.success(pageVo);
    }

    /** 分页查询: 页码, 数量, word **/
    @RequestMapping("/selectPageByWord/{current}/{size}/{word}")
    public JsonResult selectPageByWord(@PathVariable(value = "current") Long current,
                                 @PathVariable(value = "size") Long size,
                                 @PathVariable(value = "word") String word) {
        System.out.println("UserController: selectPage");
        PageVo<User> pageVo = userService.selectPage(current,size,word);
        return JsonResult.success(pageVo);
    }

    /** 查询列表: 性别比例**/
    @RequestMapping("/findSexRatio")
    public JsonResult findSexRatio() {
        System.out.println("UserController: selectCount");
        List<Map<String,Object>> list=userService.selectListWithSexRatio();
        return JsonResult.success(list);
    }


}
